package com.imooc.project.controller;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.imooc.project.dto.LoginDTO;
import com.imooc.project.entity.Account;
import com.imooc.project.mapper.AccountMapper;
import com.imooc.project.service.AccountService;
import com.imooc.project.service.ResourceService;
import com.imooc.project.vo.ResourceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Configuration
@RequestMapping("auth")
public class LoginController {


    @Autowired
    private AccountService accountService;
    @Autowired
    private ResourceService resourceService;
@RequestMapping("login")
    public String loain(String username, String password, HttpSession session,
                        RedirectAttributes attributes, Model model){
//业务逻辑要写在service当中
    LoginDTO loginDTO = accountService.login(username, password);
    String error = loginDTO.getError();//这里是返回前端页面的错误信息的
    if (error == null) {//说明验证成功获取session
        session.setAttribute("account", loginDTO.getAccount());//保存当前人的信息
//      这里是获取到它的role_id然后进行查询他所拥有的资源和下级目录
        List<ResourceVO> resourceVOS = resourceService.listResourceByRoleId(loginDTO.getAccount().getRoleId());
    model.addAttribute("resources",resourceVOS);
    } else {
        attributes.addFlashAttribute("error", error);
    }
    return loginDTO.getPath();//这里的路径在service层就已经返回了是“/”
    }
    @RequestMapping("/error")
public  String error(){
    return "error";
    }
//    登出 要消除session
    @GetMapping("logout")
    public String logout(HttpSession session){
    session.invalidate();//消除当前人的信息
    return "redirect:/";
    }

}
